<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<style>
  /* .layui-layer-content::-webkit-scrollbar {
    display: none;
  } */
  
  .class-options {
    padding: 10px;
  }
  
  .generator-config-table {
    padding-left: 10px;
    padding-right: 10px;
  }
  
  #prevDiv {
    display: none;
    width: 99%;
  }
  
  #prevTabContent {
    padding: 0;
  }
  
  .hide {
    display: none !important;
  }
  
  pre[class*="language-"] {
    margin: 0 !important;
    border-radius: 0 !important;
  }
</style>
<link
  href="/prism/prism.css"
  rel="stylesheet" />

<div class="layui-row">
  <div class="layui-col-md4">
    <div class="layui-row generator-config-table">
      <fieldset class="layui-elem-field layui-field-title">
        <legend>模版选择</legend>
      </fieldset>
      <div
        class="layui-form"
        id="templateForm"
        style="margin-top: 10px">
        <select
          lay-filter="templateIdFilter"
          name="templateId"
          id="templateId">
          <option value="">请选择模版</option>
          <option
            th:each="codeTemplate : ${codeTemplateList}"
            th:value="${codeTemplate.id}"
          >[[${codeTemplate.templateName}]](<span style="color: cornflowerblue">[[${codeTemplate.templateType}]]</span>)</option>
        </select>
      </div>
      <table
        class="layui-hide"
        id="classConfig"
        lay-filter="classConfigFilter"></table>
    </div>
    <div class="layui-row generator-config-table">
      <fieldset class="layui-elem-field layui-field-title">
        <legend>生成属性</legend>
      </fieldset>
      <form
        class="layui-form layui-form-pane"
        id="configForm"
        action=""
        lay-filter="configForm">
        <div class="layui-form-item">
          <label class="layui-form-label">表注释</label>
          <div class="layui-input-block">
            <input
              type="text"
              id="tableComment"
              name="tableComment"
              lay-verify="required"
              autocomplete="off"
              placeholder="请输入表注释"
              class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">前缀</label>
          <div class="layui-input-block">
            <input
              type="text"
              id="prefix"
              name="prefix"
              autocomplete="off"
              placeholder="请输入前缀(可为空)"
              class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">作者</label>
          <div class="layui-input-block">
            <input
              type="text"
              id="author"
              name="author"
              lay-verify="required"
              autocomplete="off"
              placeholder="请输入作者"
              class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">模块名</label>
          <div class="layui-input-block">
            <input
              type="text"
              id="moduleName"
              name="moduleName"
              lay-verify="required"
              autocomplete="off"
              placeholder="请输入模块名"
              class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-input-block">
            <button
              type="button"
              class="layui-btn layui-btn-primary"
              id="showPrev">预览
            </button>
            <button
              type="button"
              class="layui-btn"
              id="download">下载
            </button>
            <button
              type="button"
              class="layui-btn layui-btn-normal"
              id="generate">生成
            </button>
          </div>
        </div>
      </form>
    </div>
  </div>
  <div class="layui-col-md8">
    <div
      class="layui-tab layui-tab-card"
      id="prevDiv"
      lay-filter="prevTab">
      <ul
        class="layui-tab-title"
        id="prevTabs">
      </ul>
      <div
        class="layui-tab-content"
        id="prevTabContent">
      </div>
    </div>
  </div>
</div>

<script src="/prism/prism.js"></script>

<script
  type="text/html"
  id="classConfigToolbar">
  生成类
</script>

<script
  type="text/html"
  id="methodConfigToolbar">
  生成方法
</script>

<script>
  layui.use(['layer', 'util', 'form', 'element'], function () {
    var $ = layui.$,
      layer = layui.layer,
      util = layui.util,
      table = layui.table,
      form = layui.form,
      element = layui.element,
      dataSource = $('.searchForm #dataSource'),
      tableName = $('.searchForm #tableName'),
      searchTemplate = $('#templateForm #templateId'),
      tableSchema = $('.searchForm #tableSchema'),
      tableComment = tableName.find('option:selected').attr('data-tableComment'),
      prefix = window.localStorage.getItem('prefix') || '',
      author = window.localStorage.getItem('author') || '',
      packageName = window.localStorage.getItem('packageName') || '',
      moduleName = window.localStorage.getItem('moduleName') || '',
      projectPath = window.localStorage.getItem('projectPath') || '',
      commonPackage = window.localStorage.getItem('commonPackage') || '',
      defaultTemplateId = window.localStorage.getItem('templateId') || ''

    $("#templateForm #templateId").val(defaultTemplateId);
    
    form.render()

    $('#configForm #prefix').val(prefix)
    $('#configForm #author').val(author)
    $('#configForm #packageName').val(packageName)
    $('#configForm #commonPackage').val(commonPackage)
    $('#configForm #moduleName').val(moduleName)
    $('#configForm #projectPath').val(projectPath)
    $('#configForm #tableComment').val(tableComment)

    //展示已知数据
    var tableInit = table.render({
      title: '选择需要生成的类',
      url: '/code/template/file/list',
      id: 'classConfig',
      elem: '#classConfig',
      toolbar: '#classConfigToolbar',
      defaultToolbar: [''],
      where: {
        templateId: defaultTemplateId
      },
      page: false,
      cols: [
        [ //标题栏
          {
            type: 'checkbox'
          },
          {
            field: 'fileName',
            title: '全选'
          },
          {
            field: 'fileType',
            title: '文件后缀'
          }
        ]
      ],
      even: true
    })

    form.on('select(templateIdFilter)', function (data) {
      var templateId = data.value
      tableInit.reload({
        where: {
          templateId: templateId
        }
      })
      window.localStorage.setItem('templateId', templateId)
    })

    //一些事件监听
    element.on('tab(prevTab)', function (data) {
      // var type = $(this).data('type')
      // $('.prev-content').removeClass('layui-show')
      // $('#' + type + '_content').addClass('layui-show')
    })

    function setLocal() {
      var data = form.val('configForm')

      window.localStorage.setItem('prefix', data.prefix)
      window.localStorage.setItem('author', data.author)
      window.localStorage.setItem('packageName', data.packageName)
      window.localStorage.setItem('commonPackage', data.commonPackage)
      window.localStorage.setItem('moduleName', data.moduleName)
      window.localStorage.setItem('projectPath', data.projectPath)
    }

    $('#showPrev').on('click', function () {
      $('#prevDiv').hide()
      $('#prevTabs').html('')
      $('#prevTabContent').html('')

      // 存localstorage
      setLocal()

      var data = form.val('configForm'),
        classConfigCheckStatus = table.checkStatus('classConfig')

      classConfigCheckStatus.data && classConfigCheckStatus.data.forEach((item, index) => {
        var defaultContent = index === 0 ? 'layui-show' : ''
        var fileType = ['ts', 'tsx', 'vue'].includes(item.fileType) ? 'js' : item.fileType
        var content = '<pre><code id="' +
          item.id + '_code" class="language-' + fileType + '"></code></pre>'
        var options = {
          title: item.fileName,
          content: content,
          id: item.id
        }
        element.tabAdd('prevTab', options)
        
        var json = $.extend({}, data, {
          id: dataSource.val(),
          tableName: tableName.val(),
          templateId: searchTemplate.val(),
          tableSchema: tableSchema.val(),
          templateName: item.fileName
        })
        var param = Object.keys(json).map(function (key) {
          // body...
          return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
        }).join('&')

        $.get(
          '/generator/prev', param,
          function (response) {
            $('#' + item.id + '_code').text(response.data)
            Prism.highlightElement($('#' + item.id + '_code')[0])
            $('#' + item.id + '_tab').removeClass('hide')
            if (index === 0) {
              element.tabChange('prevTab', item.id)
            }
          }
        )
        $('#prevDiv').show()
      })
    })

    // 下载
    $('#download').on('click', function () {
      // 存localstorage
      setLocal()

      var data = form.val('configForm'),
        classConfigCheckStatus = table.checkStatus('classConfig')

      var json = $.extend({}, data, {
        id: dataSource.val(),
        tableName: tableName.val(),
        templateId: searchTemplate.val(),
        tableSchema: tableSchema.val(),
        backend: classConfigCheckStatus.data && classConfigCheckStatus.data.map(item => {
          return item.fileName
        })
      })
      var param = Object.keys(json).map(function (key) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
      }).join('&')

      // $.get('/generator/download', param)
      window.location.href = '/generator/download?' + param
    })

    $('#generate').on('click', function () {
      // 存localstorage
      setLocal()

      var data = form.val('configForm'),
        classConfigCheckStatus = table.checkStatus('classConfig')

      var json = $.extend({}, data, {
        id: dataSource.val(),
        tableName: tableName.val(),
        templateId: searchTemplate.val(),
        tableSchema: tableSchema.val(),
        backend: classConfigCheckStatus.data && classConfigCheckStatus.data.map(item => {
          return item.fileName
        })
      })
      var param = Object.keys(json).map(function (key) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
      }).join('&')

      $.get(
        '/generator/generate', param,
        function (response) {
          layer.msg(response.data ? response.data : response.msg, {
            time: 2000,
            icon: response.data ? 1 : 2
          })
        }
      )
    })

    table.on('checkbox(classConfigFilter)', function (obj) {
      if (obj.type === 'all') {
        $('.prev-tab').addClass('hide').removeClass('layui-this')
        $('.prev-content').removeClass('layui-show')
        if (obj.checked) {
          $('.prev-tab').removeClass('hide')
          var showTab = $('#prevTabs li').first()
          var type = showTab.data('type')
          showTab.addClass('layui-this')
          $('#' + type + '_content').addClass('layui-show')
        }
      } else {
        if (obj.checked) {
          $('#' + obj.data.fileName + '_tab').removeClass('hide')
          $('#' + obj.data.fileName + '_content').removeClass('hide')
        } else {
          $('#' + obj.data.fileName + '_tab').addClass('hide').removeClass('layui-this')
          $('#' + obj.data.fileName + '_content').removeClass('layui-show')
        }
      }
      hasChecked()
    })

    function hasChecked() {
      if ($('#prevTabs li.layui-this').length === 0) {
        var showTab = $('#prevTabs li').not('.hide').first()
        var type = showTab.data('type')
        showTab.removeClass('hide').addClass('layui-this')
        $('#' + type + '_content').addClass('layui-show')
      }
      $('#prevTabs li.layui-this').length > 0 ? $('#prevDiv').show() : $('#prevDiv').hide()
    }

    //监听头工具栏事件
    table.on('toolbar(classConfigFilter)', function (obj) {
      var checkStatus = table.checkStatus(obj.config.id),
        data = checkStatus.data //获取选中的数据
      switch (obj.event) {
        case 'generateClass':
          break
      }
    })

    //展示已知数据
    var methodTable = table.render({
      title: '选择需要生成的类',
      id: 'methodConfig',
      elem: '#methodConfig',
      toolbar: '#methodConfigToolbar',
      defaultToolbar: [''],
      cols: [
        [ //标题栏
          {
            type: 'checkbox'
          },
          {
            field: 'methodName',
            title: '全选'
          },
          {
            field: 'title',
            title: '方法名'
          }
        ]
      ],
      data: [{
        'methodName': 'get',
        'title': '查询',
        'LAY_CHECKED': true
      }, {
        'methodName': 'page',
        'title': '分页',
        'LAY_CHECKED': true
      }, {
        'methodName': 'list',
        'title': '列表',
        'LAY_CHECKED': true
      }, {
        'methodName': 'insert',
        'title': '新增',
        'LAY_CHECKED': true
      }, {
        'methodName': 'update',
        'title': '修改',
        'LAY_CHECKED': true
      }, {
        'methodName': 'delete',
        'title': '删除',
        'LAY_CHECKED': true
      }],
      skin: 'line', //表格风格
      even: true
    })
  })
</script>
</html>
